﻿//=====================================================================================
// All Rights Reserved , Copyright © JYH 2013
//=====================================================================================
using System;
using System.Net;
using System.IO;
using System.CodeDom;
using Microsoft.CSharp;
using System.CodeDom.Compiler;
using System.Text;
using System.Web.Services.Description;

namespace JYH.Framework
{
    /// <summary>
    /// 动态调用WebService 帮助类
    /// </summary>
    public class WebServiceHelper
    {
        /// <summary>
        /// 调用示例
        /// </summary>
        /// <param name="methodName"></param>
        /// <param name="args"></param>
        /// <param name="msg"></param>
        /// <param name="types"></param>
        /// <returns></returns>
        //private static object InvokeConfigService(string methodName, object[] args, out string msg, params Type[] types)
        //{
        //    msg = "";
        //    try
        //    {
        //        var url = GD.ConfigServiceUrl;

        //        var nameSpace = "SchoolManager.ConfigService";

        //        return WSHelper.InvokeWebService(url, nameSpace, methodName, args, types);
        //    }
        //    catch (Exception ex)
        //    {
        //        msg = ex.Message;
        //        return null;
        //    }
        //}

        /// <summary>
        /// 动态调用web服务
        /// </summary>
        /// <param name="url">WSDL地址</param>
        /// <param name="methodname">方法名(模块名)</param>
        /// <param name="args">参数列表,无参数为null</param>
        /// <param name="nameSpace">默认值JYH.WebService</param>
        /// <returns>object</returns>
        public static object InvokeWebService(string url, string nameSpace, string methodname, object[] args, params Type[] types)
        {
            return WebServiceHelper.InvokeWebService(url, nameSpace, null, methodname, args, types);
        }

        public static object CreateWebService(string url, string nameSpace, string classname)
        {
            if (classname == null || classname == "")
            {
                classname = WebServiceHelper.GetClassName(url);
            }
            //获取服务描述语言(WSDL)
            WebClient wc = new WebClient();
            Stream stream = wc.OpenRead(url + "?WSDL");//【1】
            ServiceDescription sd = ServiceDescription.Read(stream);//【2】
            ServiceDescriptionImporter sdi = new ServiceDescriptionImporter();//【3】
            sdi.AddServiceDescription(sd, "", "");
            CodeNamespace cn = new CodeNamespace(nameSpace);//【4】
            //生成客户端代理类代码
            CodeCompileUnit ccu = new CodeCompileUnit();//【5】
            ccu.Namespaces.Add(cn);
            sdi.Import(cn, ccu);
            CSharpCodeProvider icc = new CSharpCodeProvider();//【6】
            //ICodeCompiler icc = csc.CreateCompiler();//【7】
            //设定编译器的参数
            CompilerParameters cplist = new CompilerParameters();//【8】
            cplist.GenerateExecutable = false;
            cplist.GenerateInMemory = true;
            cplist.ReferencedAssemblies.Add("System.dll");
            cplist.ReferencedAssemblies.Add("System.XML.dll");
            cplist.ReferencedAssemblies.Add("System.Web.Services.dll");
            cplist.ReferencedAssemblies.Add("System.Data.dll");
            //编译代理类
            CompilerResults cr = icc.CompileAssemblyFromDom(cplist, ccu);//【9】
            if (true == cr.Errors.HasErrors)
            {
                System.Text.StringBuilder sb = new StringBuilder();
                foreach (CompilerError ce in cr.Errors)
                {
                    sb.Append(ce.ToString());
                    sb.Append(System.Environment.NewLine);
                }
                throw new System.Exception(sb.ToString());
            }

            //生成代理实例,并调用方法
            System.Reflection.Assembly assembly = cr.CompiledAssembly;
            System.Type t = assembly.GetType(nameSpace + "." + classname, true, true);
            object obj = System.Activator.CreateInstance(t);//【10】
            return obj;
        }

        /// <summary>
        /// 动态调用web服务
        /// </summary>
        /// <param name="url">WSDL服务地址</param>
        /// <param name="classname">类名</param>
        /// <param name="methodname">方法名(模块名)</param>
        /// <param name="nameSpace">默认值JYH.WebService</param>
        /// <param name="args">参数</param>
        /// <returns>object</returns>
        public static object InvokeWebService(string url, string nameSpace, string classname, string methodname, object[] args, params Type[] types)
        {
            //string @namespace = "wangsx.test";
            if (classname == null || classname == "")
            {
                classname = WebServiceHelper.GetClassName(url);
            }
            //获取服务描述语言(WSDL)
            WebClient wc = new WebClient();
            Stream stream = wc.OpenRead(url + "?WSDL");//【1】
            ServiceDescription sd = ServiceDescription.Read(stream);//【2】
            ServiceDescriptionImporter sdi = new ServiceDescriptionImporter();//【3】
            sdi.AddServiceDescription(sd, "", "");
            CodeNamespace cn = new CodeNamespace(nameSpace);//【4】
            //生成客户端代理类代码
            CodeCompileUnit ccu = new CodeCompileUnit();//【5】
            ccu.Namespaces.Add(cn);
            sdi.Import(cn, ccu);
            CSharpCodeProvider icc = new CSharpCodeProvider();//【6】
            //ICodeCompiler icc = csc.CreateCompiler();//【7】
            //设定编译器的参数
            CompilerParameters cplist = new CompilerParameters();//【8】
            cplist.GenerateExecutable = false;
            cplist.GenerateInMemory = true;
            cplist.ReferencedAssemblies.Add("System.dll");
            cplist.ReferencedAssemblies.Add("System.XML.dll");
            cplist.ReferencedAssemblies.Add("System.Web.Services.dll");
            cplist.ReferencedAssemblies.Add("System.Data.dll");
            //编译代理类
            CompilerResults cr = icc.CompileAssemblyFromDom(cplist, ccu);//【9】
            if (true == cr.Errors.HasErrors)
            {
                System.Text.StringBuilder sb = new StringBuilder();
                foreach (CompilerError ce in cr.Errors)
                {
                    sb.Append(ce.ToString());
                    sb.Append(System.Environment.NewLine);
                }
                throw new System.Exception(sb.ToString());
            }

            //生成代理实例,并调用方法
            System.Reflection.Assembly assembly = cr.CompiledAssembly;
            System.Type t = assembly.GetType(nameSpace + "." + classname, true, true);
            object obj = System.Activator.CreateInstance(t);//【10】
            //TODO:新加入的，解决HTTP417问题，测试如果有问题，先找这一句
            System.Net.ServicePointManager.Expect100Continue = false;
            if (types == null || types.Length == 0)
            {
                System.Reflection.MethodInfo mi = t.GetMethod(methodname);
                return mi.Invoke(obj, args);
            }
            else
            {
                System.Reflection.MethodInfo mi = t.GetMethod(methodname, types);
                return mi.Invoke(obj, args);
            }
        }
        /// < summary>          

        /// 动态调用web服务 

        /// < /summary>          

        /// < param name="url">WSDL服务地址< /param>

        /// < param name="classname">类名< /param>  

        /// < param name="methodname">方法名 < /param>  

        /// < param name="args">参数< /param> 

        /// < returns>< /returns>

        public static object InvokeWebService(string url, string classname, string methodname, object[] args)

        {

            string @namespace = "JYH.WebService";

            if ((classname == null) || (classname == ""))

            {

                classname = GetClassName(url);

            }

            try

            {                   //获取WSDL   

                WebClient wc = new WebClient();

                Stream stream = wc.OpenRead(url + "?WSDL");

                ServiceDescription sd = ServiceDescription.Read(stream);

                ServiceDescriptionImporter sdi = new ServiceDescriptionImporter();

                sdi.AddServiceDescription(sd, "", "");

                CodeNamespace cn = new CodeNamespace(@namespace);

                //生成客户端代理类代码          

                CodeCompileUnit ccu = new CodeCompileUnit();

                ccu.Namespaces.Add(cn);

                sdi.Import(cn, ccu);

                CSharpCodeProvider icc = new CSharpCodeProvider();

                //设定编译参数                 

                CompilerParameters cplist = new CompilerParameters();

                cplist.GenerateExecutable = false;

                cplist.GenerateInMemory = true;

                cplist.ReferencedAssemblies.Add("System.dll");

                cplist.ReferencedAssemblies.Add("System.XML.dll");

                cplist.ReferencedAssemblies.Add("System.Web.Services.dll");

                cplist.ReferencedAssemblies.Add("System.Data.dll");

                //编译代理类                 

                CompilerResults cr = icc.CompileAssemblyFromDom(cplist, ccu);

                if (true == cr.Errors.HasErrors)

                {

                    System.Text.StringBuilder sb = new System.Text.StringBuilder();

                    foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors)

                    {

                        sb.Append(ce.ToString());

                        sb.Append(System.Environment.NewLine);

                    }

                    throw new Exception(sb.ToString());

                }

                //生成代理实例，并调用方法   

                System.Reflection.Assembly assembly = cr.CompiledAssembly;

                Type t = assembly.GetType(@namespace + "." + classname, true, true);

                object obj = Activator.CreateInstance(t);

                System.Reflection.MethodInfo mi = t.GetMethod(methodname);

                return mi.Invoke(obj, args);

                // PropertyInfo propertyInfo = type.GetProperty(propertyname);     

                //return propertyInfo.GetValue(obj, null); 

            }

            catch (Exception ex)

            {

                throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace));

            }

        }
        /// <summary>
        /// 获取WebService类型
        /// </summary>
        /// <param name="url">http://localhost:9001/JyshtWebService.asmx</param>
        /// <returns></returns>
        private static string GetClassName(string url)
        {
            string[] parts = url.Split('/');
            string[] pps = parts[parts.Length - 1].Split('.');
            return pps[0];
        }
    }
}
